import type { Router, RouteRecordRaw } from 'vue-router';
import { usePermissionStoreWithOut } from '/@/store/modules/permission';
import { PageEnum } from '/@/enums/pageEnum';
import { useUserStoreWithOut } from '/@/store/modules/user';
// import { getAppDetails } from '/@/api/app';
import { getAccessableAppByToken } from '/@/api/user';
import { PAGE_NOT_FOUND_ROUTE ,FULL_PAGE_NOT_FOUND_ROUTE} from '/@/router/routes/basic';

const LOGIN_PATH = PageEnum.BASE_LOGIN;
const BASE_HOME = PageEnum.BASE_HOME;

const whitePathList: PageEnum[] = [LOGIN_PATH];

export function createPermissionGuard(router: Router) {
  const userStore = useUserStoreWithOut();
  const permissionStore = usePermissionStoreWithOut();
  router.beforeEach(async (to, from, next) => {


    let token = userStore.getToken;
    const appId = userStore.getLoginApp?.currentId;
    const hasAppList = userStore.getLoginApp?.accessableList.length > 0;

    // 第三方系统通过iframe嵌入管理系统页面，传递认证信息
    if(to.query.token) {
      userStore.setToken(to.query?.token as string)
      userStore.setClientId(to.query?.clientId as string)
      token = to.query?.token as string;
      //====TODO get client_info by clientId and set it into store
      const { data: { clientId, clientName, clientManagerIds}, code} = await getAccessableAppByToken({clientId: to.query.clientId});
      if (code == 200) {
        userStore.setLoginApp({
          accessableList: [{ clientId: clientId, clientName: clientName}],
          clientManagerId: clientManagerIds || [],
          currentId: clientId,
        })
      }
    }

    // Whitelist can be directly entered
    if (whitePathList.includes(to.path as PageEnum)) {
      if (to.path === LOGIN_PATH && token) {
        const isSessionTimeout = userStore.getSessionTimeout;
        try {
          if (hasAppList && !appId) {
            next();
            return;
          }
          const homePath = await userStore.loginEnd(true);
          if (!isSessionTimeout) {
            next((to.query?.redirect as string) || homePath || '/');
            return;
          }
        } catch {}
      }
      next();
      return;
    }
    // token does not exist
    if (!token) {
      // You can access without permission. You need to set the routing meta.ignoreAuth to true
      if (to.meta.ignoreAuth) {
        next();
        return;
      }
      // debugger;
      // redirect login page
      const redirectData: { path: string; replace: boolean; query?: Recordable<string> } = {
        path: LOGIN_PATH,
        replace: true,
      };
      if (to.path) {
        redirectData.query = {
          ...redirectData.query,
          redirect: to.path,
        };
      }
      next(redirectData);
      return;
    }
    
    // Jump to the 404 page after processing the login
    // if (
    //   from.path === LOGIN_PATH &&
    //   to.name === PAGE_NOT_FOUND_ROUTE.name &&
    //   to.fullPath !== (userStore.getUserInfo.homePath || PageEnum.BASE_HOME)
    // ) {
    //   next(userStore.getUserInfo.homePath || PageEnum.BASE_HOME);
    //   return;
    // }

    // get userinfo while last fetch time is empty
    if (userStore.getLastUpdateTime === 0) {
      try {
        // await userStore.getUserInfoAction();
      } catch (err) {
        next();
        return;
      }
    }

    if (permissionStore.getIsDynamicAddedRoute) {
      next();
      return;
    }

    if (to.path != BASE_HOME) {
      await userStore.getUserInfoAction()
      const routes = await permissionStore.buildRoutesAction();
      // console.log('routes', routes)
      routes.forEach((route) => {
        router.addRoute(route as unknown as RouteRecordRaw);
      });
      router.addRoute(PAGE_NOT_FOUND_ROUTE as unknown as RouteRecordRaw);
      router.addRoute(FULL_PAGE_NOT_FOUND_ROUTE as unknown as RouteRecordRaw);
  
      permissionStore.setDynamicAddedRoute(true);
    }

    if (to.path == BASE_HOME) next();


    if (to.name === PAGE_NOT_FOUND_ROUTE.name) {
      // 动态添加路由后，此处应当重定向到fullPath，否则会加载404页面内容
      next({ path: to.fullPath, replace: true, query: to.query }); 
    } else {
      const redirectPath = (from.query.redirect || to.path) as string;
      const redirect = decodeURIComponent(redirectPath);
      const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect };
      next(nextData);
    }
  });
}
